/**
 * 串行任务示例
 */
var fs = require('fs'),
    request = require('request'),
    htmlparser = require('htmlparser'),
    configFileName = './rss_feeds.txt';

function checkForRSSFile() {
    fs.exists(configFileName, function(exists) {
        if (!exists) {
            return next(new Error('Missing Rss file ' + configFileName));
        }
        next(null, configFileName);
    });
}
//选出一个url
function readRssFile(configFileName) {
    fs.readFile(configFileName, function(err, data) {
        if (err) {
            return next(err);
        }
        var list = data.toString().replace(/^\s+|\s+$/g, '').split('\n');
        next(null, list[Math.floor(Math.random() * list.length)]);
    });
}

function downloadRSSFeed(feedUrl) {
    request({
        uri: feedUrl
    }, function(err, res, body) {
        if (err) {
            return next(err);
        }
        if (res.statusCode !== 200) {
            return next(new Error('Abnormal response status code'));
        }
        next(null, body);
    });
}

function parseRSSFeed(rss) {
	console.log(rss);
    var handler = new htmlparser.RssHandler();
    var parser = new htmlparser.Parser(handler);
    parser.parseComplete(rss);
    if (!handler.dom.items.length) {
        return next(new Error('No RSS item found'));
    }
    handler.dom.items.forEach(function(v){
		console.log(v.title);
    	console.log(v.link);
    	console.log('----------');
    });
    
}
var tasks = [checkForRSSFile, readRssFile, downloadRSSFeed, parseRSSFeed];

function next(err, result) {
    if (err) {
        throw err;
    }
    var currentTask = tasks.shift();
    if (currentTask) {
        currentTask(result);
    }
}

next();
